﻿using System;
using System.Diagnostics;
using System.Management.Automation;
using System.Management.Automation.Host;
using DotNet.DevOps.Tasks.Util;

namespace DotNet.DevOps.Tasks.Cmdlets
{
    class PowershellCmdletLogger : ILog
    {
        private Cmdlet cmdlet;

        public PowershellCmdletLogger(Cmdlet cmdlet)
        {
            this.cmdlet = cmdlet;
        }

        public void LogInfo(string msg)
        {
            var stampedMsg = string.Format("[{0}] - {1}", DateTime.Now.TimeOfDay, msg);

            if (cmdlet.CommandRuntime.Host != null)
            {
                cmdlet.CommandRuntime.Host.UI.WriteLine(stampedMsg);
            }
            else
            {
                Console.WriteLine(stampedMsg);
            }
        }

        public void LogWarning(string msg)
        {
            var stampedMsg = string.Format("[{0}] - {1}", DateTime.Now.TimeOfDay, msg);

            if (cmdlet.CommandRuntime.Host != null)
            {
                cmdlet.CommandRuntime.Host.UI.WriteWarningLine(stampedMsg);
            }
            else
            {
                WriteLine(stampedMsg, ConsoleColor.Yellow);
            }
        }

        public void LogError(Exception exception)
        {
            cmdlet.WriteError(new ErrorRecord(exception, "Error", ErrorCategory.InvalidData, cmdlet));
        }

        private void WriteLine(string line, ConsoleColor textColor)
        {
            var orgColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine(line);
            Console.ForegroundColor = orgColor;
        }
    }
}
